package com.lcn.core.db;

import com.lcn.comm.domain.TxTransactionLocal;
import com.lcn.comm.framework.task.TaskGroupManager;
import com.lcn.comm.framework.task.TxTask;
import com.lcn.comm.service.db.CallClose;
import com.lcn.comm.service.db.DataSourceService;
import com.weibo.api.motan.util.LoggerUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * <p>类说明</p>
 *
 * @author 张峰 zfvip_it@163.com
 * @create: 2017-12-25 11:05
 */
public class LCNConnectionProxy extends AbstractConnection {

    private DataSourceService dataSourceService;

    /**
     * 事务组id
     */
    private String groupId;

    /**
     * 请求超时时间
     */
    private int requestTimeOut;

    /**
     * 当前连接task
     */
    private TxTask waitTask;

    /**
     * 初始化连接
     *
     * @param connection
     */
    public LCNConnectionProxy(Connection connection, DataSourceService dataSourceService, CallClose callClose) {
        this.connection = connection;
        this.dataSourceService = dataSourceService;
        this.callClose = callClose;
        TxTransactionLocal txTransactionLocal = TxTransactionLocal.current();
        groupId = txTransactionLocal.getGroupId();
        requestTimeOut = txTransactionLocal.getRequestTimeout();
        String requestId = txTransactionLocal.getRequestId();
        //创建等待任务
        waitTask = TaskGroupManager.getInstance().createTask(groupId, requestId);
    }

    /**
     * 事务处理
     *
     * @throws SQLException
     */
    protected void transaction() throws SQLException {
        //添加定时检查事务线程
        Timer timer = addSchedule();
        //开始等待通知
        waitTask.waitTask();
        timer.cancel();
        //获取任务结果
        int state = waitTask.getState();
        if (state == 1) {//提交
            connection.commit();
        } else {
            //回滚
            rollback();
        }
        closeConnection();
        waitTask.remove();
    }

    /**
     * 添加定时检查事务线程
     */
    private Timer addSchedule() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                int res = dataSourceService.cleanNotifyTransaction(getGroupId(), waitTask.getRequestId());
                if (res == 1 || res == 0) {
                    waitTask.setState(res);
                    waitTask.signalTask();
                    LoggerUtil.info("自动唤醒连接池task，groupId[{}],requestId[{}]", groupId, waitTask.getRequestId());
                }
            }
        }, requestTimeOut + 100);
        return timer;
    }

    /**
     * 用于关闭时检查是否未删除
     *
     * @return TxTask任务对象
     */
    public TxTask getWaitTask() {
        return waitTask;
    }

    /**
     * 事务组id
     *
     * @return 事务组Id
     */
    public String getGroupId() {
        return groupId;
    }
}
